package com.liangge.essaysite.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.liangge.essaysite.bean.SiteProperty;
import com.liangge.essaysite.controller.ArticleController;
import com.liangge.essaysite.service.SitePropertyService;
import com.liangge.essaysite.util.AgentKeys;
import com.liangge.essaysite.util.CfgUtils;

/**
 * 初始化系统配置属性
 * 从数据库siteproperties表中的值初始化到common.properties
 * @author liangge
 */
public class PropertiesInitListener implements ServletContextListener {
	private static Logger logger = LoggerFactory.getLogger(PropertiesInitListener.class);
	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		//获取spring容器
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
		SitePropertyService sitePropertyService = (SitePropertyService)context.getBean("sitePropertyService");
		//获取所有siteproperties
		List<SiteProperty> resultList = sitePropertyService.selectAllSiteProperties();
		//获取common.properties配置文件
		Configuration config = CfgUtils.getCommonCfg();
		for(SiteProperty siteProperty : resultList){
			//将property_name组合成基本项中的值 如indexpagesize组合成property.indexpagesize.101
			Object[] sitePropertyParts = new Object[3];
			sitePropertyParts[0] = AgentKeys.P_PREFIX;
			sitePropertyParts[1] = siteProperty.getPropertyName();
			sitePropertyParts[2] = siteProperty.getPropertyId();
			//组合
			String sitePropertyKey = StringUtils.join(sitePropertyParts, AgentKeys.KEYS_SEPARATE);
			//初始化更新配置
			config.setProperty(sitePropertyKey, siteProperty.getPropertyValue());
		}
		logger.info("siteproperties init success!");
	}

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
	}

}
